//
//  RecommendViewController.m
//  Cooking
//
//  Created by dllo on 15/8/22.
//  Copyright (c) 2015年 ZP.Y. All rights reserved.
//

#import "RecommendViewController.h"
#import "AppMacro.h"
#import "QCRound.h"
#import "RecommendCollectionViewCell.h"
#import "AsyncGetConnection.h"
#import "RecommendModel.h"
#import "CookViewController.h"
#import "MBProgressHUD.h"
#import "DaPeiViewController.h"

@interface RecommendViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, QCRoundDelegate, MBProgressHUDDelegate>

@property (retain, nonatomic) NSMutableArray   *collectionArray;
@property (retain, nonatomic) NSMutableArray   *dayArray;
@property (retain, nonatomic) UICollectionView *collection;
@property (retain, nonatomic) UILabel          *foodName;
@property (retain, nonatomic) UILabel          *englishName;
@property (retain, nonatomic) UILabel          *goodBad;
@property (retain, nonatomic) MBProgressHUD    *HUD;
@property (assign, nonatomic) NSInteger        page;
@property (retain, nonatomic) UILabel          *dayLabel;
@property (retain, nonatomic) UILabel          *yearLabel;
@property (retain, nonatomic) UILabel          *lunarBar;
@property (retain, nonatomic) UIPageControl    *pageControl;
@end

@implementation RecommendViewController

- (void)dealloc {
    [_collectionArray release];
    [_collection release];
    [_dayArray release];
    [_foodName release];
    [_englishName release];
    [_goodBad release];
    [_HUD release];
    [_dayLabel release];
    [_yearLabel release];
    [_lunarBar release];
    [_pageControl release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectionArray = [NSMutableArray array];
        self.dayArray = [NSMutableArray array];
        self.page = 1;
    }
    return self;
}

//自定义navigationBar,视图将要出现时,隐藏自身的navigationBar
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:255 / 255.0 green:125 / 255.0 blue:67 / 255.0 alpha:1];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:18], NSForegroundColorAttributeName : [UIColor whiteColor]}];
    self.navigationItem.title = @"推荐";
    
    // 添加一个食材搭配
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"食材搭配" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction:)];
    [self.navigationController.navigationItem.rightBarButtonItem setTintColor:[UIColor yellowColor]];
    
    [self createCollectionView];
    [self createPageControl];
    [self beginConnect];
    [self createIntroduce];
}

-(void)rightAction:(id)sender
{
    DaPeiViewController *daPei = [[[DaPeiViewController  alloc]init]autorelease];
    daPei.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:daPei animated:YES];
    
    
}


#pragma mark - 
#pragma mark 网络数据请求
- (void)beginConnect {
    //菜品数据解析
    [AsyncGetConnection asyncGetConnectionWithURL:[NSString stringWithFormat:@"http://121.40.54.242:80/HandheldKitchen/api/more/tblcalendaralertinfo!homePageInfo.do?phonetype=2&page=%ld&pageRecord=10&is_traditional=0", (long)_page] parameters:nil block:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = [dic objectForKey:@"data"];
        for (NSDictionary *value in array) {
            RecommendModel *recModel = [[RecommendModel alloc] init];
            [recModel setValuesForKeysWithDictionary:value];
            [_collectionArray addObject:recModel];
            [recModel release];
            // 第一次创建时候,强行调用方法
            [self scrollViewDidEndDecelerating:nil];
        }
        [_collection reloadData];
        [_HUD hide:YES afterDelay:0.1];
    }];
    
    //日历请求
    //首先获取系统当前的时间
    NSDate *senddate = [NSDate date];
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYYMMdd"];
    NSString *locationString =[dateformatter stringFromDate:senddate];
    NSLog(@"locationString:%@",locationString);
    NSString *yearStr = [locationString substringToIndex:4];
    NSRange month = {4, 2};
    NSString *monthStr = [locationString substringWithRange:month];
    NSRange day = {6, 2};
    NSString *dayStr = [locationString substringWithRange:day];
    [dateformatter release];
    
    //服务器分流,根据情况选择不同的接口
//http://121.41.117.95:80/HandheldKitchen/api/more/tblcalendaralertinfo!get.do?year=2015&month=08&day=20&page=1&pageRecord=10&is_traditional=0
    
//http://121.41.88.194:80/HandheldKitchen/api/more/tblcalendaralertinfo!get.do?year=2015&month=08&day=21&page=1&pageRecord=10&is_traditional=0
    
    //适宜以及时间数据解析
    [AsyncGetConnection asyncGetConnectionWithURL:[NSString stringWithFormat:@"http://121.40.54.242:80/HandheldKitchen/api/more/tblcalendaralertinfo!get.do?year=%@&month=%@&day=%@&page=1&pageRecord=10&is_traditional=0", yearStr, monthStr, dayStr] parameters:nil block:^(NSData *data) {
        NSDictionary *dayDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        //用上面这种方式,是两个不同的内存地址,当后面的内存被释放时,_dataArray依然存在
        [_dayArray addObjectsFromArray:[dayDic objectForKey:@"data"]];
        //这种方式,是两个指针,指向同一个内存地址,当后面的内存被释放,会出现野指针
//        _dayArray = [dayDic objectForKey:@"data"];
        //先获取数据,在创建视图,否则,赋值容易出现错误
        
        //日
        NSString *dayStr = [[_dayArray firstObject] objectForKey:@"GregorianCalendar"];
        NSString *newStr = [dayStr substringFromIndex:8];
        _dayLabel.text = newStr;

        //年
        NSString *yearStr = [[_dayArray firstObject] objectForKey:@"GregorianCalendar"];
        NSString *newYear = [yearStr substringToIndex:7];
        _yearLabel.text = newYear;
        
        //农历
        _lunarBar.text = [NSString stringWithFormat:@"农历%@", [[_dayArray firstObject] objectForKey:@"LunarCalendar"]];
        
        //事宜
        NSString * bad = [[_dayArray firstObject] objectForKey:@"alertInfoAvoid"];
        _goodBad.text = [NSString stringWithFormat:@"宜:%@  忌:%@", [[_dayArray firstObject] objectForKey:@"alertInfoFitting"], bad];

    }];
}

- (void)createIntroduce {
    //日期
    self.dayLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 30, 50, 50)];
//    dayLabel.backgroundColor = [UIColor grayColor];
    _dayLabel.textColor = [UIColor whiteColor];
    _dayLabel.shadowColor = [UIColor grayColor];
    _dayLabel.shadowOffset = CGSizeMake(1.5, 1.5);
//    dayLabel.backgroundColor = [UIColor grayColor];
    _dayLabel.font = [UIFont systemFontOfSize:40.0];
    _dayLabel.textAlignment = NSTextAlignmentCenter;
    
//    阴影
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, WIDTH - 55, 140)cornerRadius:10];
    _dayLabel.layer.shadowPath = path.CGPath;
//    dayLabel.layer.shadowRadius = 20.0;
    _dayLabel.layer.shadowOpacity = 0.25;
    [self.view addSubview:_dayLabel];
    [_dayLabel release];
    
    //年月
    self.yearLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, _dayLabel.frame.origin.y + _dayLabel.frame.size.height, 50, 25)];
    _yearLabel.font = [UIFont systemFontOfSize:13.0];
    _yearLabel.textColor = [UIColor whiteColor];
    _yearLabel.shadowColor = [UIColor grayColor];
    _yearLabel.shadowOffset = CGSizeMake(1.5, 1.5);
    _yearLabel.textAlignment = NSTextAlignmentCenter;
//    yearLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_yearLabel];
    [_yearLabel release];
    
    //竖条
    UILabel *barLabel = [[UILabel alloc] initWithFrame:CGRectMake(_dayLabel.frame.origin.x + _dayLabel.frame.size.width + 5, 25, 2, 75)];
    barLabel.backgroundColor = [UIColor whiteColor];
    barLabel.alpha = 0.7;
    [self.view addSubview:barLabel];
    [barLabel release];
    
    //农历
    self.lunarBar = [[UILabel alloc] initWithFrame:CGRectMake(barLabel.frame.origin.x + barLabel.frame.size.width + 5, 30, 120, 20)];
//    lunarBar.backgroundColor = [UIColor grayColor];
    _lunarBar.textColor = [UIColor whiteColor];
    _lunarBar.shadowColor = [UIColor grayColor];
    _lunarBar.shadowOffset = CGSizeMake(1.5, 1.5);
    [self.view addSubview:_lunarBar];
    [_lunarBar release];
    
    //事宜
//        self.goodBad = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH, lunarBar.frame.origin.y + lunarBar.frame.size.height + 5, WIDTH, 20)];
    self.goodBad = [[UILabel alloc] initWithFrame:CGRectMake(barLabel.frame.origin.x + barLabel.frame.size.width + 5, _lunarBar.frame.origin.y + _lunarBar.frame.size.height + 5 - 7, WIDTH / 1.5, 60)];
    _goodBad.font = [UIFont systemFontOfSize:12.0];
    _goodBad.numberOfLines = 0;
    _goodBad.textColor = [UIColor whiteColor];
//    _goodBad.backgroundColor = [UIColor grayColor];
    _goodBad.shadowColor = [UIColor grayColor];
    _goodBad.shadowOffset = CGSizeMake(1.5, 1.5);
    [self.view addSubview:_goodBad];
    [_goodBad release];
    
    //横条
    UILabel *acrossLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, _yearLabel.frame.origin.y + _yearLabel.frame.size.height + 5, WIDTH - 60, 2)];
    acrossLabel.backgroundColor = [UIColor whiteColor];
    acrossLabel.alpha = 0.7;
    acrossLabel.shadowColor = [UIColor grayColor];
    acrossLabel.shadowOffset = CGSizeMake(1.5, 1.5);
    [self.view addSubview:acrossLabel];
    [acrossLabel release];
    
    //菜名
    self.foodName = [[UILabel alloc] initWithFrame:CGRectMake(30, acrossLabel.frame.origin.y + acrossLabel.frame.size.height + 5, WIDTH, 20)];
//    _foodName.backgroundColor = [UIColor grayColor];
    _foodName.textColor = [UIColor whiteColor];
    _foodName.shadowColor = [UIColor grayColor];
    _foodName.shadowOffset = CGSizeMake(1.5, 1.5);
    [self.view addSubview:_foodName];
    [_foodName release];
    
    //菜英文
    self.englishName = [[UILabel alloc] initWithFrame:CGRectMake(30, _foodName.frame.origin.y + _foodName.frame.size.height + 5, WIDTH, 20)];
    _englishName.font = [UIFont systemFontOfSize:14];
    _englishName.textColor = [UIColor whiteColor];
    _englishName.shadowColor = [UIColor grayColor];
    _englishName.shadowOffset = CGSizeMake(1.5, 1.5);
//    _englishName.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_englishName];
    [_englishName release];
}

//推荐菜品轮播collectionView
- (void)createCollectionView {
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 64 - 49);
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 49 - 64) collectionViewLayout:flowLayout];
    _collection.backgroundColor = [UIColor whiteColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.pagingEnabled = YES;
    _collection.bounces = NO;
//    collection.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:_collection];
    [_collection registerClass:[RecommendCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
    [_collection release];
    
    //加载等待
    self.HUD = [[MBProgressHUD alloc] init];
    _HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
    _HUD.delegate = self;
    _HUD.backgroundColor = [UIColor clearColor];
    _HUD.detailsLabelText = @"努力加载中...";
    _HUD.dimBackground = YES;
}

#pragma mark -
#pragma mark PageControl
- (void)createPageControl {
    //创建PageControl
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake((WIDTH - 100) / 2, HEIGHT / 1.4, 100, 30)];
    
    _pageControl.numberOfPages = 10;
    _pageControl.userInteractionEnabled = NO;
    [self.view addSubview:_pageControl];
    [_pageControl release];
}

#pragma mark - 
#pragma mark collectionView协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _collectionArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    RecommendCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    RecommendModel *recommend = [_collectionArray objectAtIndex:indexPath.item];
    
    [cell sendValueWithModel:recommend];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CookViewController *cookVC = [[CookViewController alloc] init];
    RecommendModel *recommend = [_collectionArray objectAtIndex:indexPath.item];
    cookVC.myID = recommend.vegetable_id;
    cookVC.nameStr = recommend.name;
    cookVC.recommendModel = recommend;
    [self.navigationController pushViewController:cookVC animated:YES];
    [cookVC release];
}

#pragma mark -
#pragma mark 滚动结束,改变参数
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    NSLog(@"%f", _collection.contentOffset.x);
    NSInteger itemNum = _collection.contentOffset.x / _collection.frame.size.width;
    
    RecommendModel *recommend = [_collectionArray objectAtIndex:itemNum];
    //给菜名赋值
    _foodName.text = recommend.name;
    _englishName.text = recommend.englishName;
    
   //判断滑动到每组最后一张时,跳回第一位置
    if (scrollView == self.collection) {
         //pageControl判断,
        if (scrollView.contentOffset.x == 0  || scrollView.contentOffset.x / WIDTH == 10) {
            self.pageControl.currentPage = 0;
        } else {
            self.pageControl.currentPage = (NSInteger)(scrollView.contentOffset.x / WIDTH) % 10;
        }
//        NSLog(@"1111====%f", scrollView.contentOffset.x);
//        NSLog(@"222===%f", WIDTH);
//        NSLog(@"333===%ld", self.pageControl.currentPage);
        
        //判断滚动,刷新数据
        if (scrollView.contentOffset.x >(self.collectionArray.count- 2)*WIDTH) {
            self.page = self.page+1;

            //加载等待
            self.HUD = [[MBProgressHUD alloc] init];
            _HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
            _HUD.delegate = self;
            _HUD.backgroundColor = [UIColor clearColor];
            _HUD.detailsLabelText = @"更新推荐中...";
            _HUD.dimBackground = YES;
            //解析
            [self beginConnect];
            }
        }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
